<?php
require_once '../vendor/autoload.php';

use Workerman\Worker;
use Workerman\Lib\Timer;
use PHPSocketIO\SocketIO;

require_once './SingleMysql.php';
require_once './SingleRedis.php';

$box_socketio = new SocketIO(12122);
$mysql = SingleMysql::getInstance();
//$redis = SingleRedis::getInstance();
$config = require './config.php';
$redis = new Redis();
$redis->connect($config['redis']['db_host'], $config['redis']['db_port']);
//为了让超时的服务永不超时？有用吗
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1);

//全局变量 所有连接的box数组
$box_sockets = array();
//开始
$box_socketio->on('workerStart', function () use ($box_socketio) {
    //设置非阻塞判断
    $lock = 1;
    //定时循环读取队列中的数据，并发送给box端修改
    Timer::add(0.5, function () use ($box_socketio,&$lock) {
        global $redis, $mysql, $box_sockets;
        if(!$lock)
        {
            return;
        }
        if ($redis) {
            $lock = 0;
            //循环读取数据
            while (1) {
                if (!$mq_pop = $redis->rPop('editMQ')) {
                    $lock = 1;
                    return;
                }
                $data = json_decode($mq_pop, true);
                if (!isset($data['editor'])) {
                    continue;
                }
                //盒子端同屏修改
                $res2 = $mysql->select("did,end_time")->from('rszh_meeting_live_speech')->where('meeting_tag= :mid')->bindValues(array('mid' => $data['mid']))->row();
                //获取盒子端的socket
                $box_socket = $box_sockets[$res2['did']];
                if (!empty($box_socket) && empty($res2['endtime'])) {
                    //获取全部信息
                    $all_message = '';
                    $count = $redis->hget($data['mid'] . '_state', 'lower') - 1;
                    for ($i = $count; $i >= 1; $i--) {
                        if (strlen($all_message) >= 600) {
                            break;
                        }
                        $datas = json_decode($redis->hget($data['mid'], $i), true);
                        $str = $datas['ed_txt'] ? trim($datas['ed_txt']) : trim($datas['or_txt']);
                        if (strlen($str . $all_message) >= 2048) {
                            break;
                        }
                        $last_datas = json_decode($redis->hget($data['mid'], $i - 1), true);
                        if ($datas['sc'] != $last_datas['sc']) {
                            $all_message = ("\n\t" . $str) . $all_message;
                            continue;
                        }
                        $all_message = $str . $all_message;
                    }
                    if ($n_pos = strpos($all_message, "\n") === 0) {
                        $all_message = substr($all_message, $n_pos);
                    }
                    echo $all_message;
                    $box_socket->emit('boxedit', $all_message);
                }
            }
            $lock = 1;
        }
    });
});

//事件
$box_socketio->on('connection', function ($socket) use ($box_socketio) {
    //盒子功能
    $socket->on('boxlogin', function ($data) use ($socket) {
        global $box_sockets, $mysql;
        //echo $data ."\n";
        if (!$msg = json_decode($data, true)) {
            return;
        }
        //校验 记录日志
        foreach ($msg as $value) {
            if (!$value) {
                return;
            }
        }
        $socket->did = $msg['box_id'];
        $quary = "UPDATE `rszh_equipment` SET `connection`= 1,`update_time`=" . "'" . time() . "'" . " WHERE equipmentid = " . $msg['box_id'];
        $mr = $mysql->query($quary);
        //更新存入数据库

        $box_sockets[$msg['box_id']] = $socket;
        echo $socket->did . '登录' . "\n";
    });
    $socket->on('boxlogout', function ($data) use ($socket) {
        global $mysql;
        if ($socket->did) {
            $quary = "UPDATE `rszh_equipment` SET `connection`= 2,`update_time`=" . "'" . time() . "'" . " WHERE equipmentid = " . "'" . $socket->did . "'";
            $mr = $mysql->query($quary);
            $socket->did = null;
            $socket->disconnect();
            echo $socket->did . '登出' . "\n";
        }
    });
    $socket->on('boxtranstart', function ($data) use ($socket) {
        // global $hezhu_socket;
        // //盒子开始录音
        // $meeting_id = $data;
        // $hezhu_socket[$meeting_id] = $socket;
        // echo $meeting_id;
    });
    $socket->on('boxtranstatus', function ($data) use ($socket) {
        global $mysql;
        //echo $data;
        $msg = json_decode($data, true);
        if (!$msg) {
            return;
        }
        $list = json_decode($msg['filelist'], true);
        if (!$list) {
            return;
        }
        $filelist = array();
        try {
            foreach ($list as $meeting_id) {
                $real_query = "select id,transition_state,filename,is_manual from `rszh_meeting_live_speech` where meeting_tag='" . $meeting_id . "'";
                $result = $mysql->query($real_query);
                if (!$result) {
                    $filelist[$meeting_id] = [
                        "filename" => '',
                        "transtatus" => '',
                        "transpersent" => ''
                    ];
                } else {
                    $filename = $result[0]['filename'];
                    if ($result[0]['is_manual'] == 1) {
                        $filename = $filename . '.pcm';
                    }
                    $filelist[$meeting_id] = [
                        "filename" => $filename,
                        "transtatus" => $result[0]['transition_state'] == 0 ? 1 : $result[0]['transition_state'],
                        "transpersent" => $result[0]['transition_state'] == 2 ? "100%" : "0%"
                    ];
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        $return = [
            'token' => $msg['token'],
            'filelist' => $filelist
        ];
        //var_dump($return);
        $return = json_encode($return);
        $socket->emit('boxtranstatus', $return);
    });
    $socket->on('disconnect', function ($data) use ($socket) {
        global $mysql;
        echo "一个用户断开了" . "\n";
        //echo $socket->did;
        // $msg = json_decode($data, true);
        // if (!$msg) {
        //     return;
        // }
        if ($socket->did) {
            echo $socket->did;
            $quary = "UPDATE `rszh_equipment` SET `connection`= 3,`update_time`=" . "'" . time() . "'" . " WHERE equipmentid = " . "'" . $socket->did . "'";
            $mr = $mysql->query($quary);
        }
    });
});

header("ALLOW-CONTROL-ALLOW-ORIGIN:*");
// 如果不是在根目录启动，则运行runAll方法
if (!defined('GLOBAL_START')) {
    Worker::runAll();
}
